import { defineStore } from 'pinia'

export const useSettingsStore = defineStore('settings', {
    state: () => ({
        theme: localStorage.getItem('theme') || 'light',
        language: localStorage.getItem('language') || 'zh-CN',
        itemsPerPage: parseInt(localStorage.getItem('itemsPerPage')) || 10,
        notificationsEnabled: localStorage.getItem('notificationsEnabled') !== 'false',
        units: {
            weight: localStorage.getItem('weightUnit') || 'kg',
            volume: localStorage.getItem('volumeUnit') || 'l',
            length: localStorage.getItem('lengthUnit') || 'cm'
        }
    }),

    getters: {
        getCurrentTheme: (state) => state.theme,
        getCurrentLanguage: (state) => state.language,
        getItemsPerPage: (state) => state.itemsPerPage,
        getNotificationsEnabled: (state) => state.notificationsEnabled,
        getUnit: (state) => (type) => state.units[type]
    },

    actions: {
        setTheme(theme) {
            this.theme = theme
            localStorage.setItem('theme', theme)
            // 可以在这里应用主题到DOM
            document.documentElement.setAttribute('data-theme', theme)
        },

        setLanguage(language) {
            this.language = language
            localStorage.setItem('language', language)
        },

        setItemsPerPage(count) {
            this.itemsPerPage = count
            localStorage.setItem('itemsPerPage', count.toString())
        },

        toggleNotifications(enabled) {
            this.notificationsEnabled = enabled
            localStorage.setItem('notificationsEnabled', enabled.toString())
        },

        setUnit(type, unit) {
            if (this.units.hasOwnProperty(type)) {
                this.units[type] = unit
                localStorage.setItem(`${type}Unit`, unit)
            }
        },

        // 重置所有设置到默认值
        resetSettings() {
            this.theme = 'light'
            this.language = 'zh-CN'
            this.itemsPerPage = 10
            this.notificationsEnabled = true
            this.units = {
                weight: 'kg',
                volume: 'l',
                length: 'cm'
            }

            // 更新localStorage
            localStorage.setItem('theme', this.theme)
            localStorage.setItem('language', this.language)
            localStorage.setItem('itemsPerPage', this.itemsPerPage.toString())
            localStorage.setItem('notificationsEnabled', this.notificationsEnabled.toString())
            localStorage.setItem('weightUnit', this.units.weight)
            localStorage.setItem('volumeUnit', this.units.volume)
            localStorage.setItem('lengthUnit', this.units.length)

            // 应用主题
            document.documentElement.setAttribute('data-theme', this.theme)
        }
    }
}) 